﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System;

[Serializable]
public class TransformWeight
{
    public TWPair[] pairs = new TWPair[4];
}
[Serializable]
public class TWPair : IComparable<TWPair>
{
    public Transform bone;
    public float weight;
    public TWPair() { }
    public TWPair(Transform bone, float weight)
    {
        this.bone = bone;
        this.weight = weight;
    }
    public int CompareTo(TWPair other)
    {
        if (weight > other.weight) return 1;
        else if (weight < other.weight) return -1;
        else return 0;
    }
    public TWPair copy
    {
        get { return new TWPair(bone, weight); }
    }
}

public class CalVertexBoneWeight : MonoBehaviour
{
    VerticesSeletor vs;
    SkinnedMeshRenderer smr;
    public TransformWeight tw;
    public List<TWPair> distancesOrigin;
    void Start()
    {
        smr = GetComponent<SkinnedMeshRenderer>();
        vs = GetComponent<VerticesSeletor>();
        vs.selectChange += CalBoneWeights;
    }
    void CalBoneWeights(int b)
    {
        var vertex = vs.GetPos(b);
        var bones = smr.bones;

        List<TWPair> distances = new List<TWPair>();
        foreach (var bone in bones)
        {
            var dis = Vector3.Distance(vertex, bone.position);            
            distances.Add(new TWPair(bone, dis));
        }
        distancesOrigin = new List<TWPair>();
        foreach (var dis in distances)
        {
            distancesOrigin.Add(dis.copy);
        }
        distances.Sort( );
        distances.Reverse();
        while (distances.Count > 4)
        {
            distances.RemoveAt(0);
        }
        float amount = 0f;
        foreach (var dis in distances)
        {
            amount += dis.weight;
        }
        var weights = new List<float>();
        foreach (var dis in distances)
        {
            dis.weight= dis.weight / amount;
        }
        for (int i = 0; i < distances.Count; i++)
        {
            tw.pairs[i] = distances[i];
        }
    }
}
